package com.zcoj.annotation.aspect;

import com.zcoj.api.exception.ContestOnGoingException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ContestInProgressAspect {

    private boolean contestInProgress = false;

    @Pointcut("@annotation(com.zcoj.annotation.ContestInProgress) || within(@org.springframework.web.bind.annotation.RestControllerAdvice *)")
    public void contestInProgress() {}

    @Around("contestInProgress()")
    public Object checkContestInProgress(ProceedingJoinPoint joinPoint) throws Throwable {
        if (contestInProgress) {
            throw new ContestOnGoingException();
        }
        try {
            contestInProgress = true;
            return joinPoint.proceed();
        } finally {
            contestInProgress = false;
        }
    }

    public void setContestInProgress(boolean contestInProgress) {
        this.contestInProgress = contestInProgress;
    }

}
